package cetc54.zhtx.server;

import cetc54.zhtx.entity.HeartBeat;
import cetc54.zhtx.start.ServerListenStatus;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * 心跳机制客户端
 *
 * @author lipeng
 */
@Slf4j
public class HeartBeatServer {

    private HeartBeat heartBeat;

    public HeartBeatServer(HeartBeat heartBeat, ServerListenStatus serverListenStatus) {
        this.heartBeat = heartBeat;
        startServer(serverListenStatus);
    }

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;


    /**
     * 启动服务器
     */
    private void startServer(ServerListenStatus serverListenStatus) {
        //主线程池
         bossGroup = new NioEventLoopGroup();
        //工作线程池
         workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .childHandler(new ServerInitializedHander(serverListenStatus));
            //绑定端口 开始监听
            ChannelFuture channelFuture = serverBootstrap.bind(heartBeat.getStandbyIp(), heartBeat.getPort());
            log.info("主备心跳机制启动,端口:{}------开始接收主机发送的心跳包", heartBeat.getPort());
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("心跳机制启动失败", e);
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }


    /**
     * 关闭服务器
     */
    public void stopServer(){
        if(bossGroup!=null&&workerGroup!=null){
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
